﻿using ADODB;
using fuzhu;
using LH.Model.ST;
using SqlSuarEntity;
using SqlSugar;
using SqlSugar.Extensions;
using System.Data;
using System.Security.Cryptography;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.XXXEntities;
using ZDEntity;

namespace Yonyou.U8.BO
{

    public class RdRecord32VM : ST_Rdrecord32
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public bool bWMS = false;
        public string cDatabase = "";

        public RdRecord32VM(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

       

        public  RetModel2 AddVerify()
        {
            try
            {
                string idcheck = "";
            
                foreach(Body body in bodies)
                {
                    body.editprop = "A";
                }
              
                if (!Rdrecord32DALCO.AddRdrecord32(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    ////审核失败后，检查是否有采购入库单生成，如果有，则删除
                    //string cerr2 = "";
                    //if (!string.IsNullOrEmpty(id))
                    //{
                    //    Rdrecord32DALCO.VerifyRdrecord32(id, xmlConfig, "delete", out cerr2);
                    //}
                   
                    return DBService.ReErrObject("新增失败：" + err);
                }
                else
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {
                        DateTime dDate = DbHelper.GetDbDate(head.ddate);
                        int iid = DbHelper.GetDbInt(id);
                        db.Updateable<rdrecord32>()
                  .SetColumns(u => new rdrecord32()
                  {
                      dVeriDate = dDate,
                      cHandler = head.cmaker
                  })
                  .Where(u => u.ID == iid)
                  .ExecuteCommand();
                        ////不是wms的情况，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，删除
                        //if (!bWMS)
                        //{

                        //    if (ccode != head.ccode && head.ccode != WMSPara.rd01Code)
                        //    {
                        //        //单据编码选项判断
                        //        string sql = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='0303'");
                        //        int iRepeat = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                        //        if (iRepeat == 1)
                        //        {
                        //            string cerr2 = "";
                        //            Rdrecord32DALCO.VerifyRdrecord32(id, xmlConfig, "unverify,delete", out cerr2);
                        //            return DBService.ReOKObject("单据已生成，重复");
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    //wms的情况，因为保存是无单据号，根据传入的parentid进行判断。默认字段使用扩展自定义项10
                        //    string cParentid = head.cdefine10;
                        //    if (!string.IsNullOrEmpty(cParentid))
                        //    {
                        //        //检查cParentid 是否存在
                        //        string sqlcx = string.Format(@"select count(*) sl from rdrecord32 a  where  a.cdefine10='{0}' and a.id <>'{1}'", cParentid, id);
                        //        int icntUniq = DbHelper.GetDbInt(db.Ado.GetScalar(sqlcx));
                        //        if (icntUniq > 0)
                        //        {
                        //            Rdrecord32DALCO.VerifyRdrecord32(id, xmlConfig, "unverify,delete", out _);
                        //            return DBService.ReOKObject("之前单据已生成，重复");
                        //        }
                        //    }

                        //}
                    }
                }
                //生成的id赋值
                head.id = id;

                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }

        }


         
        public string GetRd32Info()
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    //检查是否有货位管理
                    Warehouse warehouse = db.Queryable<Warehouse>().Where(x => x.cWhCode == head.cwhcode).First();
                    


                   for (int i = 0; i < bodies.Count; i++)
                     {
                        string cInvCode = bodies[i].cinvcode;
                        WMS_GetSource source = new WMS_GetSource();
                        if (head.csource == "发货单")
                        {
                            
                              int iSourceid =DbHelper.GetDbInt(bodies[i].idlsid);
                                source = db.Queryable<DispatchLists>()
                                .InnerJoin<DispatchList>((a, b) => a.DLID == b.DLID && a.iDLsID == iSourceid) 
                                .Select((a, b) => new WMS_GetSource
                                { 
                                    ID = b.DLID,
                                    cPTCode =b.cSTCode,
                                    cCusCode= b.cCusCode,
                                    iExchRate = b.iExchRate,
                                    cCode =b.cDLCode,
                                    cDepCode =b.cDepCode,
                                    cPersonCode=b.cPersonCode,
                                    cSOCode = a.cordercode,
                                    cexch_name = b.cexch_name,
                                    cBusType = b.cBusType,
                                    iTaxRate  = a.iTaxRate,
                                    dDate= b.dDate,
                                    cInvCode = a.cInvCode,
                                    cUnitID = a.cUnitID,
                                    cMemo = b.cMemo,
                                    cbMemo =a.cMemo, 
                                    iChangeRate = a.iInvExchRate,
                                    iSosid = a.iSOsID,
                                    isorowno = a.iorderrowno,
                                    cItem_class = a.cItem_class,
                                    cItemCode = a.cItemCode,
                                    cItemName = a.cItemName,
                                    cItemCName =a.cItem_CName  ,
                                    irowno = (int?)a.irowno,
                                }).First();
                            if (source == null )
                            {
                                return string.Format("第{0}行发货单ID不正确，查询不到到货单", (i + 1).ToString());
                            } 
                        } 
                        else
                        {
                            //没有处理来料检验单
                            return "无来源单据，无需处理";
                        
                        }
                        if (i == 0 && source!=null)
                        { 
                            head.cstcode = source.cPTCode;
                            head.ccuscode = source.cCusCode;
                            head.cdepcode = source.cDepCode;
                            head.cpersoncode = source.cPersonCode;
                            head.cordercode = source.cSOCode;
                            head.cdlcode = DbHelper.GetDbString(source.ID);
                            head.cbustype = source.cBusType;
                            head.cmemo = source.cMemo;
                           

                        }

                        if ( source.cInvCode != bodies[i].cinvcode)
                        {
                            return $"第{(i + 1).ToString()}行,发货单号{source.cCode},行号{source.irowno},发货单产品{source.cInvCode}和传入产品{cInvCode}不一致";
                        }

                        //没有检查自由项,是否和来源订单一样
                          bodies[i].cinvcode = source.cInvCode;
                        //销售出库单，没有价格
                        //销售出库单的，追溯信息
                        bodies[i].cbdlcode = source.cCode;
                        bodies[i].cpesocode = source.cSOCode;
                        bodies[i].ipesoseq =DbHelper.GetDbString(source.isorowno);
                        bodies[i].ipesodid = DbHelper.GetDbString(source.iSosid); 
                        bodies[i].isotype = "0";
                        bodies[i].iordercode = source.cSOCode;
                        bodies[i].iorderdid = DbHelper.GetDbString(source.iSosid);
                        bodies[i].iorderseq = DbHelper.GetDbString(source.isorowno);
                        bodies[i].iordertype = "1";


                        bodies[i].citemcname = source.cItemCName;
                        bodies[i].citemcode = source.cItemCode;
                        bodies[i].citem_class = source.cItem_class;
                        bodies[i].cname = source.cItemName;
                        bodies[i].cassunit = source.cUnitID;
                        //货位处理
                        if (warehouse.bWhPos)
                        {
                            bodies[i].iposflag = "1";
                            if (string.IsNullOrWhiteSpace(bodies[i].cposition))
                            {
                                return string.Format("第{0}行订单物料和{1}没有货位", (i + 1).ToString(), cInvCode);
                            }
                        }
                        else
                        {
                            bodies[i].iposflag = "0";
                            bodies[i].cposition = null;
                        }
                        //
                        bodies[i].inquantity = bodies[i].iquantity;

                        InvProperty invProperty = new InventoryVM().GetInvProperty(cInvCode, bodies[i].dmadedate, bodies[i].dvdate);
                            if (invProperty==null)
                            {
                                return string.Format("第{0}行订单物料和{1}不存在", (i + 1).ToString(), cInvCode);
                            }
                            //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                            if (invProperty.iGroupType!="0")
                            {
                                 //辅助计量单位来源于来源单据，如果没有取库存单位
                                if (string.IsNullOrEmpty(bodies[i].cassunit))
                                {
                                    bodies[i].cassunit = invProperty.cSTComUnitCode;
                                }
                                 
                                if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(source.iChangeRate)))
                                    {
                                    bodies[i].iinvexchrate = invProperty.iChangRate;
                                }
                                else
                                {
                                    bodies[i].iinvexchrate = DbHelper.GetDbString(source.iChangeRate);
                                }
                                bodies[i].inum = (DbHelper.GetDbdecimal(bodies[i].iquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate)).ToString("0.000000");
                            }
                            else
                        {
                            bodies[i].inum = "";
                        }

                            //是否批次管理
                            if (!invProperty.bInvBatch)
                            {
                                bodies[i].cbatch = "";
                            }
                            else if (string.IsNullOrEmpty(bodies[i].cbatch))
                            {
                                return string.Format("第{0}行订单物料{1}有批次管理，未录入批次", (i + 1).ToString(), cInvCode);
                            }
                            //自由项，未处理
                         
                        //有效期管理,根据生产日期或者失效日期推算 
                           if(invProperty.bInvQuality)
                          {
                             if (string.IsNullOrEmpty(bodies[i].dmadedate) && string.IsNullOrEmpty(bodies[i].dvdate))
                            {
                                return string.Format("第{0}行订单物料生产日期或者失效日期未录入", (i + 1).ToString());
                            }
                             else
                            {
                                bodies[i].dvdate =DbHelper.GetDbDate(invProperty.dVDate).ToString("yyyy-MM-dd");
                                bodies[i].imassdate =DbHelper.GetDbString(invProperty.iMassDate);
                                bodies[i].cmassunit = DbHelper.GetDbString(invProperty.cMassUnit);
                                bodies[i].dexpirationdate = DbHelper.GetDbDate(invProperty.dExpeireDate).ToString("yyyy-MM-dd"); ;
                                bodies[i].iexpiratdatecalcu = DbHelper.GetDbString(invProperty.iexpiratdatecalcu);
                            }
                            

                        }
                           else
                        {
                            bodies[i].iexpiratdatecalcu = "0";
                        }


                    }
                     
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
           
                
               
            
            
            return "ok";
        }


        /// <summary>
        /// 读取发货单的idlsid
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int  GetiDLsid(string cDLCode,int irowno)
        {
             

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                var dlsid = db.Queryable<DispatchLists>()
                                .InnerJoin<DispatchList>((a, b) => a.DLID == b.DLID && a.irowno == irowno && b.cDLCode == cDLCode)
                                .Select((a, b) => a.iDLsID).First();
                 

                if (dlsid == null)
                {
                    return 0;
                }
                else
                {
                    return DbHelper.GetDbInt(dlsid);
                }

            }

        }

        /// <summary>
        /// 检查单号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from RdRecord32 where ccode='{0}' ", head.ccode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));

                 
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }

         
    }
}
